<?php

namespace App\Exports;

use App\Models\Download;
use App\Models\LotteryRecord;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class LotteryRecordExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query()
    {
        $query = LotteryRecord::query()
            ->with(['user.address', 'award'])
            ->whereHas('lottery', function ($q) {
                return $q->where('id', \Arr::get($this->request, 'lottery_id'));
            })
            ->where('award_id', \Arr::get($this->request, 'award_id'));

        return $query->orderByDesc('id');
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        /** @var LotteryRecord $value */
        $address = $value->user->address;
        $remark = json_decode($value->remark, true);

        return [
            $value->id,
            $value->award->name,
            $value->user->mobile,
            $value->created_at->toDateTimeString(),
            $value->status->description,
            $address ? $address->mobile : '未设置',
            $address ? $address->name : '未设置',
            $address ? $address->address : '未设置',
            \Arr::get($remark, 'express_name'),
            \Arr::get($remark, 'express_no'),
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            'ID',
            '奖品名称',
            '中奖用户',
            '中奖时间',
            '发放状态',
            '收货手机号',
            '收货姓名',
            '收货地址地址',
            '快递名称(可编辑)',
            '快递单号(可编辑)',
        ];
    }
}
